﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Schema;
using AutoMapper;
using AutoMapper.Configuration;
using HT.Future.Application;
using HT.Future.Common;
using HT.Future.Entities;
using HT.Future.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;

namespace HT.Future.TxApi.Controllers
{
    /// <summary>
    /// 商品服务控制器
    /// </summary>
    [ApiVersion("1.0")]
    [Authorize]
    [Route("api/[controller]")]
    public class ProductController : BaseController
    {
        private readonly IProductService _service;
        private readonly ILogger<ProductController> _logger;

        public ProductController(IMapper mapper, IProductService service, ILogger<ProductController> logger) : base(mapper)
        {
            this._service = service;
            this._logger = logger;
        }

        /// <summary>
        /// 获取商品类型列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("types")]
        public async Task<ApiResult<List<ProductTypeDto>>> GetProductTypes()
        {
            var list = await _service.GetListAsync<ProductType>();
            return _mapper.Map<List<ProductType>, List<ProductTypeDto>>(list.OrderBy(a => a.Sort).ToList());
        }

        #region 不用这里的逻辑

        ///// <summary>
        ///// 新增商品类型
        ///// </summary>
        ///// <param name="type">商品类型实体</param>
        ///// <returns></returns>
        //[HttpPost("type")]
        //public async Task<ApiResult<ProductTypeDto>> CreateProductType([FromBody]ProductType type)
        //{
        //    var isExist = await _service.IsExistProductTypeAsync(type.Name);
        //    if (isExist)
        //    {
        //        return new ApiResult<ProductTypeDto>(false, Common.ApiResultStatusCode.Success, null, $"已存在名称为[{type.Name}]类型！");
        //    }
        //    await _service.AddAsync(type);
        //    return _mapper.Map<ProductType, ProductTypeDto>(type);
        //}

        ///// <summary>
        ///// 删除商品类型
        ///// </summary>
        ///// <param name="id">类型id</param>
        ///// <returns></returns>
        //[HttpDelete("type/{id}")]
        //public async Task<ApiResult> DeleteProductType(int id)
        //{
        //    var isExist = await _service.IsExistProductTypeAsync(id);
        //    if (isExist)
        //    {
        //        return new ApiResult(false, Common.ApiResultStatusCode.Success, $"类型下存在商品，不可以被删除!");
        //    }
        //    await _service.DeleteAsync(new ProductType { Id = id });
        //    return Ok();
        //}

        ///// <summary>
        ///// 更新商品类型
        ///// </summary>
        ///// <param name="type">商品类型实体</param>
        ///// <returns></returns>
        //[HttpPut("type/{id}")]
        //public async Task<ApiResult> PutProductType([FromBody]ProductType type)
        //{
        //    await _service.UpdateAsync(type, new[] { nameof(type.Description), nameof(type.Name), nameof(type.Sort) });
        //    return Ok();
        //}

        #endregion

        /// <summary>
        /// 更新商品类型
        /// </summary>
        /// <param name="types">商品类型列表</param>
        /// <returns></returns>
        [HttpPost("generateType")]
        public async Task<ApiResult<List<ProductTypeDto>>> GenerateProductType([FromBody]List<ProductType> types)
        {
            await _service.GenerateProductTypeAsync(types);
            var list = await _service.GetListAsync<ProductType>();
            return _mapper.Map<List<ProductType>, List<ProductTypeDto>>(list.OrderBy(a => a.Sort).ToList());
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="id">类型id</param>
        /// <param name="status">商品状态（上架/下架）</param>
        /// <param name="key">搜索关键字</param>
        /// <param name="query">分页信息</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ApiResult<object>> GetProducts(int id, [FromQuery]int status, [FromQuery]string key, [FromQuery]PagingQuery query)
        {
            var list = await _service.GetProductsAsync(id, status, key, query);
            var count = query.RecordCount;
            return new { list, count };
        }

        /// <summary>
        /// 获取商品类型下最大的商品排序码
        /// </summary>
        /// <param name="id">商品类型id</param>
        /// <returns></returns>
        [HttpGet("sort/{id}")]
        public async Task<int> GetProductMaxSortAsync(int id)
        {
            if (id == 0) return 0;
            return await _service.GetProductMaxSortAsync(id);
        }

        /// <summary>
        /// 创建商品
        /// </summary>
        /// <param name="product">商品实体</param>
        /// <param name="config">应用配置</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<Product>> CreateProduct([FromBody]Product product, [FromServices]Microsoft.Extensions.Configuration.IConfiguration config)
        {
            await UploadImagesAsync(product, config);
            await _service.CreateProductAsync(product);
            return product;
        }

        /// <summary>
        /// 更新商品
        /// </summary>
        /// <param name="product"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<Product>> UpdateProduct([FromBody]Product product, [FromServices]Microsoft.Extensions.Configuration.IConfiguration config)
        {
            await UploadImagesAsync(product, config);
            var entity = await _service.UpdateProductAsync(product);
            return entity;
        }

        /// <summary>
        /// 商品上架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("up/{id}")]
        public async Task<ApiResult> Up(int id)
        {
            var product = new Product { Id = id, Status = ProductStatus.Sale, ModifyTime = DateTime.Now };
            await _service.UpdateAsync(product, new[] { nameof(product.Status), nameof(product.ModifyTime) });
            return Content("上架成功");
        }

        /// <summary>
        /// 商品下架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("down/{id}")]
        public async Task<ApiResult> Down(int id)
        {
            var product = new Product { Id = id, Status = ProductStatus.NotSale, ModifyTime = DateTime.Now };
            await _service.UpdateAsync(product, new[] { nameof(product.Status), nameof(product.ModifyTime) });
            return Content("下架成功");
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(int id)
        {
            var product = new Product { Id = id, Status = ProductStatus.Delete, ModifyTime = DateTime.Now };
            await _service.UpdateAsync(product, new[] { nameof(product.Status), nameof(product.ModifyTime) });
            return Content("操作成功");
        }

        /// <summary>
        /// 批量上架
        /// </summary>
        /// <returns></returns>
        [HttpPut("upBatch")]
        public async Task<ApiResult> UpBatch([FromBody]List<int> ids)
        {
            var now = DateTime.Now;
            var products = await _service.GetByIdsAsync<Product>(ids.ToArray());
            products.ForEach(a =>
            {
                a.Status = ProductStatus.Sale;
                a.ModifyTime = now;
            });
            await _service.CommitAsync();
            return Content("上架成功");
        }

        /// <summary>
        /// 批量下架
        /// </summary>
        /// <returns></returns>
        [HttpPut("downBatch")]
        public async Task<ApiResult> DownBatch([FromBody]List<int> ids)
        {
            var now = DateTime.Now;
            var products = await _service.GetByIdsAsync<Product>(ids.ToArray());
            products.ForEach(a =>
            {
                a.Status = ProductStatus.NotSale;
                a.ModifyTime = now;
            });
            await _service.CommitAsync();
            return Content("下架成功");
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("deleteBatch")]
        public async Task<ApiResult> DeleteBatch([FromBody]List<int> ids)
        {
            var now = DateTime.Now;
            var products = await _service.GetByIdsAsync<Product>(ids.ToArray());
            products.ForEach(a =>
            {
                a.Status = ProductStatus.Delete;
                a.ModifyTime = now;
            });
            await _service.CommitAsync();
            return Content("删除成功");
        }




        /// <summary>
        /// 上传图片到文件服务器
        /// </summary>
        /// <param name="product"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        private async Task UploadImagesAsync(Product product, Microsoft.Extensions.Configuration.IConfiguration config)
        {
            if (product.Images == null || product.Images.Count == 0) return;
            var fileserver = config.GetSection("AppConfig:FileServer").Value;
            var images = product.Images.Where(a => a.Id == 0).Select(a =>
            {
                a.Name = Guid.NewGuid().ToString().Replace("-", "").ToLower() + ".jpg";
                return new ImagePost { Name = a.Name, Big = a.Big, Small = a.Small };
            });
            if (images.Count() == 0) return;
            _logger.LogInformation($"上传附件数：{images.Count()}，文件服务器路径：{fileserver}");
            await UtilHelper.RequestAsync($"{fileserver}/api/product", images);

        }
    }
}
